﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace World
{
    /// <summary>
    /// Summary description for ShowImage
    /// </summary>
    public class ShowImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            int countryID = 0;
            if (context.Request.QueryString["id"] != null)
            {
                countryID = int.Parse(context.Request.QueryString["id"]);
            }
            else
            {
                throw new ArgumentException("No argument specified!");
            }

            context.Response.ContentType = "image/png";

            Stream stream = ShowCountryFlag(countryID);

            byte[] buffer = new byte[4096];

            int byteSeq = stream.Read(buffer, 0, 4096);



            while (byteSeq > 0)
            {

                context.Response.OutputStream.Write(buffer, 0, byteSeq);

                byteSeq = stream.Read(buffer, 0, 4096);

            }
        }

        private Stream ShowCountryFlag(int countryID)
        {
            WorldEntities1 worldEntities = new WorldEntities1();
            Country country = worldEntities.Countries.First(c => c.CountryID == countryID);

            try
            {
                return new MemoryStream(country.Flag);
            }
            catch
            {
                return null;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}